import { Request, toast, queryParams } from '../../utils/util.js'
let request = new Request()
const app = getApp()
Component({
  data: {
    searchLocation : '',
    longitude: 0,
    latitude : 0,

    deviceList : []
  },

  methods : {
    onLoad (options) {
      let q = options.q || ''
      try{
        if (q !== '') {
          let params = queryParams(q)
          let deviceNo = params.deviceNo
          let portNo = params.portNo || 0
          wx.navigateTo({ url: '/pages/charge/index?deviceNo=' + deviceNo + '&portNo=' + portNo })
        }
      }catch(e){}
    },
    chooseLocation() {
      wx.chooseLocation({
        success: res => {
          this.setData({ searchLocation: res.name, longitude: res.longitude, latitude: res.latitude })
          this.getNearDeviceList()
        }
      })
    },

    getNearDeviceList() {
      request.get('neardevice', res => {
        if (res.success) {
          let deviceList = res.data.list
          if (deviceList.length == 0) {
            this.setData({ deviceList: null })
          } else {
            this.setData({ deviceList: deviceList })
          }
        }
      }, { longitude: this.data.longitude, latitude: this.data.latitude }).showLoading()
    }
  },
  
  pageLifetimes : {
    show() { //获取位置
      if (typeof this.getTabBar === 'function' &&
        this.getTabBar()) {
        this.getTabBar().setData({
          selectedIndex : 0
        })
      }
      
      wx.getLocation({
        success: (res) => {
          let longitude = res.longitude; 114.06031;
          let latitude = res.latitude; 22.72174;
          this.setData({ longitude: longitude, latitude: latitude })
          this.getNearDeviceList()
        },
        fail : () => {
          this.setData({ deviceList: deviceList})
        }
      })
    }
  }
  
})
